import { createSlice } from '@reduxjs/toolkit';

// 默认初始状态
const initialState = {
  // 拓扑构建相关状态
  topologyData: null,
  historyTopologies: [],
  // 网络监控相关状态
  attackerCount: 0,
  serverCount: 0,
  trafficCharts: [],
};

export const networkSlice = createSlice({
  name: 'network',
  initialState,
  reducers: {
    // 拓扑构建相关 reducers
    setTopologyData: (state, action) => {
      state.topologyData = action.payload;
    },
    setHistoryTopologies: (state, action) => {
      state.historyTopologies = action.payload;
    },
    clearTopologyData: (state) => {
      state.topologyData = null;
    },
    // 网络监控相关 reducers
    setAttackerCount: (state, action) => {
      state.attackerCount = action.payload;
    },
    setServerCount: (state, action) => {
      state.serverCount = action.payload;
    },
    setTrafficCharts: (state, action) => {
      state.trafficCharts = action.payload;
    },
    addTrafficChart: (state, action) => {
      // 确保trafficCharts是数组
      if (!Array.isArray(state.trafficCharts)) {
        state.trafficCharts = [];
      }
      state.trafficCharts.push(action.payload);
    },
    updateTrafficChart: (state, action) => {
      // 确保trafficCharts是数组
      if (!Array.isArray(state.trafficCharts)) {
        state.trafficCharts = [];
        return;
      }

      const { serverName, rxBytes, txBytes } = action.payload;
      const chartIndex = state.trafficCharts.findIndex(chart => chart.serverName === serverName);
      if (chartIndex !== -1) {
        const chart = state.trafficCharts[chartIndex];
        // 确保rxBytes和txBytes是数组
        const rxBytesArray = Array.isArray(chart.rxBytes) ? chart.rxBytes : [];
        const txBytesArray = Array.isArray(chart.txBytes) ? chart.txBytes : [];

        state.trafficCharts[chartIndex] = {
          ...chart,
          rxBytes: [
            ...rxBytesArray.slice(-19), // 保留最近20个数据点
            { time: new Date().toLocaleTimeString(), value: rxBytes }
          ],
          txBytes: [
            ...txBytesArray.slice(-19), // 保留最近20个数据点
            { time: new Date().toLocaleTimeString(), value: txBytes }
          ],
        };
      }
    },
    removeTrafficChart: (state, action) => {
      // 确保trafficCharts是数组
      if (!Array.isArray(state.trafficCharts)) {
        state.trafficCharts = [];
        return;
      }
      state.trafficCharts = state.trafficCharts.filter(chart => chart.serverName !== action.payload);
    },
    // 重置网络状态（不影响拓扑数据）
    resetNetworkState: (state) => {
      state.attackerCount = 0;
      state.serverCount = 0;
      state.trafficCharts = [];
    },
  },
});

export const {
  setTopologyData,
  setHistoryTopologies,
  clearTopologyData,
  setAttackerCount,
  setServerCount,
  setTrafficCharts,
  addTrafficChart,
  updateTrafficChart,
  removeTrafficChart,
  resetNetworkState,
} = networkSlice.actions;

export default networkSlice.reducer;